var app = getApp()
const api = require('../../utils/utils')
Page({
  data: {
    iconUrl: api.iconUrl,
    // 用户表单数据
    user: {
      realname: '', // 姓名
      // id_number: '', // 身份证号 
      username: '', // 手机号
      usertype: 'D', // 用户类型
      sms_code: '', // 验证码
      password: "", // 密码
      password2: "", // 确认密码
      allow: true, // 是否同意协议
    },
    send_status: true, // 控制发送验证码按钮 true表示可以获取
    remain_time: 60, // 间隔发送时间
    phone_number: '', // 提前获取手机号码
    is_enroll: false, // 手机号是否已经注册
    checkitems: [{
      id: 1,
      checked: false
    }],
    // 表单校验规则
    realnameRules: [{
        required: true,
        message: '请输入姓名',
        trigger: 'blur'
      },
      {
        min: 2,
        max: 14,
        message: '姓名长度在2-14个字符之间',
        trigger: 'blur'
      },
    ],
    id_numberRules: [{
        required: false,
        message: '请输入病历号',
        trigger: 'blur'
      },
      {
        pattern: '^[0-9]{17}[0-9Xx]$',
        message: '病历号不合法',
        trigger: 'blur'
      }
    ],
    usernameRules: [{
        required: true,
        message: '请输入手机号',
        trigger: 'blur'
      },
      {
        pattern: '^1[1-9][0-9]{9}$',
        message: '手机号不合法',
        trigger: 'blur'
      },
      {
        validator(rule, value, callback) {
          if (value == '' || value == undefined || value == null) {
            callback();
            return
          }
          api.request('get', `/usernames/${value}/count/`, {}, false).then(res => {
            if (res.count === 0) {
              callback();
            } else {
              callback(false);
            }
          })
        },
        message: '手机号已注册',
        trigger: 'blur'
      }
    ],
    codeRules: [{
        required: true,
        message: '请输入验证码',
        trigger: 'blur'
      },
      {
        min: 6,
        max: 6,
        message: '验证码为6个数字组成',
        trigger: 'blur'
      },
      {
        pattern: '^[0-9]+$',
        message: '验证码必须由数字组成',
        trigger: 'blur'
      },
    ],
    passwordRules: [{
        required: true,
        message: '请输入登录密码',
        trigger: 'blur'
      },
      {
        min: 8,
        max: 16,
        message: '密码长度在8-16个字符之间',
        trigger: 'blur'
      },
      {
        pattern: '^[A-Za-z0-9]+$',
        message: '密码必须由数字字母组成',
        trigger: 'blur'
      }
    ],
    password2Rules: [{
        required: true,
        message: '请确认密码',
        trigger: 'blur'
      },
      {
        validator(rule, value, callback, source) {
          const {
            password,
            password2
          } = source;
          if (password !== password2) {
            callback(false);
          }
          callback()
        },
        message: '两次密码输入不一致',
        trigger: 'change'
      }
    ],
    allowRules: [{
      required: true,
      trigger: 'blur'
    }, ],
  },

  onLoad: function (options) {
    // 设置当前导航栏标题
    wx.setNavigationBarTitle({
      title: '注册'
    })
  },
  onShow: function () {
    wx.lin.initValidateForm(this) // 表单初始化
  },
  async submit(event) {
    const toast = this.selectComponent("#mytoast")
    if (event.detail.isValidate === false) {
      toast.linShow({
        title: "输入格式错误！",
        icon: "error"
      })
      return
    }
    let source = event.detail.values
    let target = this.data.user
    Object.assign(target, source);
    await api.request('post', '/users/', target, false).then(res => {
      toast.linShow({
        title: "注册成功",
        icon: "success"
      })
      // 注册成功返回登录页面
      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
        })
      }, 1000)
    }).catch(err => {
      toast.linShow({
        title: "注册失败",
        icon: "error"
      })
    })
  },
  getPhoneNumber(event) {
    const {
      detail
    } = event
    this.setData({
      phone_number: detail.value
    })
  },
  setCheckGroup(event) {
    let items = this.data.checkitems;
    items.forEach(item => {
      if (item.id == event.detail.key) {
        item.checked = event.detail.checked;
      }
    });
    this.setData({
      checkitems: items,
    });
  },
  // 请求发送短信验证码
  send_code() {
    const toast = this.selectComponent("#mytoast")
    // 判断手机号是否已经注册
    api.request('get', `/usernames/${this.data.phone_number}/count/`, {}, false)
      .then(res => {
        // 手机号未注册则发送短信
        if (res.count === 0) {
          api.request('get', `/sms_codes/${this.data.phone_number}/`, {}, false)
            .then(res => {
              this.setData({
                send_status: false
              })
              toast.linShow({
                title: "验证码发送成功",
                icon: "success"
              })
              // 验证码倒计时
              let time = setInterval(() => {
                let remain_time = this.data.remain_time;
                remain_time--;
                this.setData({
                  remain_time: remain_time
                });
                if (remain_time == 0) {
                  clearInterval(time);
                  this.setData({
                    remain_time: 60,
                    send_status: true
                  });
                }
              }, 1000)
            })
            .catch(err => {
              toast.linShow({
                title: "验证码发送失败，请检查手机号是否正确",
                icon: "error"
              })
            })
        } else {
          toast.linShow({
            title: "手机号已注册",
            icon: 'error'
          })
        }
      })
  },
})